#include "Seed_Driver.h"
#include "hx6203sys.h"

void Seed_Init(void){
	GPIO_InitTypeDef  GPIO_InitStructure;
	DAC_InitTypeDef DAC_InitType;
	
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);//使能GPIOA时钟
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE);//使能DAC时钟
	   
	//PA5 普通IO 用于种子源使能
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//普通输出模式
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100MHz
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;//上拉
  GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化
	GPIO_ResetBits(GPIOA,GPIO_Pin_5);	//PA5置低
	
	//PA4 DAC IO 用于种子源功率控制
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;//模拟输入
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;//下拉
  GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化
	
	DAC_InitType.DAC_Trigger=DAC_Trigger_None;	//不使用触发功能 TEN1=0
	DAC_InitType.DAC_WaveGeneration=DAC_WaveGeneration_None;//不使用波形发生
	DAC_InitType.DAC_LFSRUnmask_TriangleAmplitude=DAC_LFSRUnmask_Bit0;//屏蔽、幅值设置
	DAC_InitType.DAC_OutputBuffer=DAC_OutputBuffer_Disable ;	//DAC1输出缓存关闭 BOFF1=1
  DAC_Init(DAC_Channel_1,&DAC_InitType);	 //初始化DAC通道1
	DAC_Cmd(DAC_Channel_1, ENABLE);  //使能DAC通道1
  
  DAC_SetChannel1Data(DAC_Align_12b_R, 0);  //12位右对齐数据格式设置DAC值
}

float Seed_SetVlotage(float vol){
	#define MaxDacVol 2866
	uint16_t temp=0;
	const float k = 4096/5.0f;
	temp = vol * k;
	if(temp > MaxDacVol)  temp = MaxDacVol;	//DAC输出限幅，端口最大3.5V，防止过推
	DAC_SetChannel1Data(DAC_Align_12b_R,temp);
	if(temp==MaxDacVol)	return (((float)temp/k)+0.01f);                                 /*返回值*/
	else return vol;
}

float Get_Seed_Curr(void)   
{
	float Curr;
	ADC_RegularChannelConfig(ADC3, 5, 1, ADC_SampleTime_480Cycles );
		    
	ADC_SoftwareStartConv(ADC3);		//使能指定的ADC1的软件转换启动功能	
	while(!ADC_GetFlagStatus(ADC3, ADC_FLAG_EOC ));//等待转换结束
	Curr=ADC_GetConversionValue(ADC3);	//返回最近一次ADC1规则组的转换结果
	Curr=Curr*(float)(3.3f/4096.0f/0.15f);
	Curr=Curr/1.38f;
	Seed.Curr=Curr;
	
	return Curr;	//由ADC值 换算电流
}
